<?php

class Db{
	public static function ConnectDB ($DbHost, $DbName, $DbUser, $DbPass) {
		$link = mysql_connect($DbHost, $DbUser , $DbPaDbExecutess);
		if (!$link) {
			die('Could not connect: ' . mysql_error());
		}
		$Db=mysql_select_db($DbName,$link);
		if (!$Db) {
		   die('Could not select database '.$DbName);
		}
		self::DbExecute("SET NAMES UTF8");
		return $link;
	}
	
	public static function DbFetchRow ($Query,$link=null) {
		
		if($link==null)
			$result = self::DbExecute($Query);
		else
			$result = self::DbExecute($Query,$link);
		if (!$result) {
			echo 'Could not run query: '.$Query.' '.mysql_error();
			exit;
		}
		
		if($link==null)
			$row = mysql_fetch_row($result);
		else
			$row = mysql_fetch_row($result,$link);
		return $row;
	}	
	
	public static function DbInsertId($Query,$link=null)  {
		return $link?mysql_insert_id($link):mysql_insert_id();
	}
	
	public static function DbFetchArray($Query,$link=null)  {
		
		if($link==null)
			$result = self::DbExecute($Query);
		else
			$result = self::DbExecute($Query,$link);
		if (!$result) {
			echo 'Could not run query: '.$Query.' '.mysql_error();
			exit;
		}
		$row = mysql_fetch_array($result);
		return $row;
	}
	
	public static function DbFetchAssoc($Query,$link=null)  {
		
		if($link==null)
			$result = self::DbExecute($Query);
		else
			$result = self::DbExecute($Query,$link);
		if (!$result) {
			echo 'Could not run query: '.$Query.' '.mysql_error();
			exit;
		}
		$row = mysql_fetch_assoc($result);
		return $row;
	}
	
	public static function DbExecute ($Query,$link=null) {
		global $debug;
		$inizio = microtime();
		if($link==null)
			$result = mysql_query($Query);
		else
			$result = mysql_query($Query,$link);
		$fine = microtime() - $inizio; 
		if($debug)
			echo '<div class="debug"><span class="azzurro">'.$fine.': </span>'.$Query.'</div>';
		if (!$result) {
			echo 'Could not run query: '.$Query.' '.mysql_error();
			exit;
		}
		return $result;
	}	
	
	public static function prepareSqlFieldValue($theValue, $theType="text", $theDefinedValue = "", $theNotDefinedValue = ""){
		  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
		
		  switch ($theType) {
			case "text":
			  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			  break;    
			case "long":
			case "int":
			  $theValue = ($theValue != "") ? intval($theValue) : "NULL";
			  break;
			case "double":
			  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
			  break;
			case "date":
			  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			  break;
			case "defined":
			  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
			  break;
		  }
		  return $theValue;
	}
	
}